﻿// Copyright 2013 Ronald Schlenker, www.technewlogic.de.
// 
// This file is part of Byond.
// 
// Byond is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
// 
// Byond is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Byond.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.IO;
using Byond.EnsembleLibrary;
using Byond.Frontend.Messages;
using Byond.Messages;
using Mvvm;
using System.Linq;

namespace Byond.Frontend.EnsembleBrowserNew.ViewModels
{
	public class BrowserViewModel : ViewModelBase
	{
		private readonly Library _library;
		private readonly ItemSelectionArbiter _itemSelectionArbiter;
		private readonly Func<LibraryFolder, FolderViewModel> _folderFactory;

		private void Ctor()
		{
			Refresh();
		}

		public FolderViewModel Root { get; private set; }

		public void HandleMessage(LibraryChangedMessage message)
		{
			Refresh();
		}

		public void HandleMessage(LocateEnsembleRequest message)
		{
			// TODO: Lieber FirstOrDefault? Ist garantiert, dass immer ein Item da ist?
			var patch = Root.Flatten().SelectMany(it =>
				it.Children.OfType<ItemViewModel>()).Single(it => it.FileName == message.FileName);
			patch.ExpandTreeAndSelect();
		}

		// TODO: Besseres Update machen; Performance optimieren; preserve ViewState (Selection)
		private void Refresh()
		{
			_itemSelectionArbiter.Reset();

			// backup current expansion state
			var expandedFolders = Root == null
				? new List<FolderViewModel>()
				: Root.Flatten().Where(it => it.IsExpanded).ToList();

			var rootFolder = _library.CreateRootFolder();
			var rootViewModel = _folderFactory(rootFolder);
			rootViewModel.ToggleExpansion();

			Root = rootViewModel;
			OnPropertyChanged("Root");

			// restore expansion (intersect)
			var currentFolders = Root.Flatten()
				.Where(it => expandedFolders.Any(it2 => it2.Path == it.Path))
				.ToList();
			foreach (var it in currentFolders)
				it.Expand();
		}
	}
}
